<?php

App::uses('Shell', 'Console');
App::uses('BaseParser', 'Console/Command/Task');

class LeituraHS01Task extends BaseParser {
	public $uses = array('LeiturasHs01');

	public function execute() {
		$this->out('LeituraHS01');

		$this->parse();
	}

	private function parse() {
		$contSeparate = 0;
		$this->content = explode("\n", $this->content);

		$db = $this->LeiturasHs01->getDataSource();
        $db->begin();

		foreach ($this->content as $line) {
			if ($contSeparate < 3) {
				if ($line[0] == '-')
					$contSeparate++;

				continue;
			}

			$line = trim($line);
			$line = str_replace(',','.',$line);
			$itens = preg_split("/  +/", $line);

			if (count($itens) < 6)
				continue;

			$date = $this->convertToDateSql($itens[0]);

			$sequencia = $this->getNumSequencia($date);

			$leitura = array(
				'LeiturasHs01' => array(
					'sequencia'		=> $sequencia,
					'hora'			=> $date,
					'estacao_id'	=> $this->estacaoId,
					'precipitacao'	=> $itens[1],
					'sedimentos'	=> $itens[2],
					'nivel'			=> $itens[3],
					'vazao'			=> $itens[4],
					'bateria'		=> $itens[5]
				)
			);

			if (!$this->LeiturasHs01->save($leitura)) {
				$this->out('Erro ao adicionar Leitura, erros: '.print_r($this->LeiturasHs01->validationErrors, true));
			}		
		}

		if ($db->commit() === false) {
        	$this->out('Erro ao adicionar Leitura, erros: '.print_r($this->LeiturasHs01->validationErrors, true));
    	}
	}	
}